/**
 * Created by qunxing.du on 2016/7/15.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.gdyc;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;

/**
 * 广德扬尘客户端单例模式
 */
//@Component
public class GdClient {

    private static  final  String WSDL = "http://27.50.132.176/sanitate/services/SaveYCJCService";
    private static final String NAME_SPACE_URI = "http://service.tblycjc.webservice.client.dekn.com.cn";
//    private static final int CONNECT_TIMEOUT = 60000;//毫秒
//    private static final int RECEIVE_TIMEOUT = 60000;//毫秒
//    private static Client client;
//    private Client(){}

//    public static Client getInstance(){
//        if(client == null){
//            JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//            client = dcf.createClient(GD_WSDL);
//            HTTPConduit conduit = (HTTPConduit) client.getConduit();
//            HTTPClientPolicy clientPolicy= new HTTPClientPolicy();
//            clientPolicy.setConnectionTimeout(CONNECT_TIMEOUT);
//            clientPolicy.setReceiveTimeout(RECEIVE_TIMEOUT);
//            conduit.setClient(clientPolicy);
//            log.debug("客户端实例："+ client);
//        }
//        return client;
//    }
        public static String send(String data) throws Exception{

            QName serviceName = new QName(NAME_SPACE_URI,"SaveYCJCService");
            QName portName = new QName(NAME_SPACE_URI,"SaveYCJCServiceHttpPort");
            Service service =  Service.create(serviceName);

            service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING,WSDL);
            Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,SOAPMessage.class,Service.Mode.MESSAGE);

            //创建消息
            MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
            SOAPMessage request = mf.createMessage();
            SOAPPart part = request.getSOAPPart();

            SOAPEnvelope envelope = part.getEnvelope();
            SOAPBody body = envelope.getBody();
            SOAPElement operation = body.addChildElement("saveYCJC");
            SOAPElement value = operation.addChildElement("in0");
            value.addTextNode(data);
            request.saveChanges();

            SOAPMessage response = dispatch.invoke(request);
            Document document =  response.getSOAPBody().getOwnerDocument();
            Element responseElement = (Element) document.getElementsByTagNameNS(NAME_SPACE_URI,"out").item(0);
            String result = responseElement.getTextContent();
            return result;
        }

}
